package com.cd2cd.code_template.configuration.security.loginUserService.impl;

import com.alibaba.fastjson.JSONObject;
import com.cd2cd.code_template.code_template.domain.SysAuth;
import com.cd2cd.code_template.code_template.domain.SysUser;
import com.cd2cd.code_template.code_template.domain.gen.SysAuthCriteria;
import com.cd2cd.code_template.code_template.mapper.SysAuthMapper;
import com.cd2cd.code_template.code_template.mapper.SysUserMapper;
import com.cd2cd.code_template.configuration.constants.ServiceCode;
import com.cd2cd.code_template.configuration.exceptions.ServiceBusinessException;
import com.cd2cd.code_template.configuration.security.TokenUser;
import com.cd2cd.code_template.configuration.security.loginUserService.LoadUserService.Backend;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;

@Component
public class BackendServiceImpl implements Backend {

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private SysAuthMapper sysAuthMapper;

    @Override
    public <T extends TokenUser> T loadUserByUsername(String username) {

        SysUser sysUser = sysUserMapper.findUserByUsername(username);
        if(Objects.isNull(sysUser)) {
            throw new ServiceBusinessException(ServiceCode.LOGIN_ERROR, "");
        }

        Integer userId = sysUser.getId();
        String password = sysUser.getPassword();

        // 获取当前用户权限
        List<SysAuth> auths;
        if ("admin".equals(username)) {
            SysAuthCriteria criteria = new SysAuthCriteria();
            criteria.createCriteria().andTypeEqualTo(Backend.class.getSimpleName());
            auths = sysAuthMapper.selectByExample(criteria);
        }else {
            auths = sysUserMapper.queryUserAuth(userId, Backend.class.getSimpleName());
        }


        Set<GrantedAuthority> authorities = new HashSet<>();
        auths.forEach(a->{
            authorities.add(new SimpleGrantedAuthority(a.getGuid()));
        });

        return (T) new TokenUser(userId,username, password, Backend.class, authorities);
    }

}
